package cn.chendd.utils;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * <pre>
 * 日志记录工具类
 * </pre>
 *
 * <pre>
 * modify by chendd on 2017-6-20
 *    fix->1.
 *         2.
 * </pre>
 */
public class LogUtil {
	
	public static void info(String message) {
		Log log = getLog();
		if(log.isInfoEnabled()){
			log.info("#######" + message + "#######");
		}
	}
	
	public static void debug(String message){
		Log log = getLog();
		if(log.isDebugEnabled()){
			log.debug("#######" + message + "#######");
		}
	}
	
	public static void error(String message , Exception e) {
		Log log = getLog();
		if(log.isErrorEnabled()){
			if(e != null){
				log.error("#######" + message + "#######" , e);
			} else {
				log.error("#######" + message + "#######");
			}
		}
	}
	
	public static void error(Exception e) {
		error("异常信息：" , e);
	}
	
	private static Log getLog() {
		StackTraceElement stack = findStackTrace();
		Log log = null;
		if(stack == null){
			log = LogFactory.getLog(LogUtil.class);
		} else {
			String name = stack.getClassName() + "." + stack.getMethodName() + "(" + stack.getLineNumber() + ")";
			log = LogFactory.getLog(name);
		}
		return log;
	}

	private static StackTraceElement findStackTrace() {
		StackTraceElement stackElement = null;
		StackTraceElement stacks[] = Thread.currentThread().getStackTrace();
		if(stacks == null || stacks.length == 0){
			return stackElement;
		}
		String logClassName = LogUtil.class.getName();
		boolean flag = false;
		for (StackTraceElement stack : stacks) {
			String className = stack.getClassName();
			if(logClassName.equals(className)){
				flag = true;
			}
			if(flag == true && !logClassName.equals(className)){
				stackElement = stack;
				break;
			}
		}
		return stackElement;
	}

}
